package cn.zero.test;

import cn.zero.utils.ESClientUtil;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;

public class EsTest4 {
    //    - 查询用户表
    //    - name包含：我在源码
    //    - age在1~12之间
    //    - 每页大小2
    //    - 从二页开始查
    //    - 按照age倒序
    //    - sex=1
    @Test
    public void Test()throws Exception{
        //获取链接
        TransportClient client = ESClientUtil.getClient();

        //预加载pethome
        SearchRequestBuilder builder = client.prepareSearch("pethome");

        //类型
        builder.setTypes("user");

        //bool
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //DSL查询
        boolQuery.must(QueryBuilders.matchQuery("name","源码"));//matchQuery分词过滤

        //DSL过滤
        boolQuery.filter(QueryBuilders.termQuery("sex",1));//termQuery不分词过滤

        //范围查询
        boolQuery.filter(QueryBuilders.rangeQuery("age").gte(1).lte(30));

        //设置query
        builder.setQuery(boolQuery);

        //设置分页，每页显示条数
        builder.setSize(10);

        //设置起始位置
        builder.setFrom(0);

        //排序
        builder.addSort("age", SortOrder.ASC);

        //查询
        SearchHit[] hits = builder.get().getHits().getHits();

        //遍历打印
        for (SearchHit hit: hits) {
            System.out.println(hit.getSourceAsMap());
        }


    }
}
